package com.candy.databasedocuments.controller;

import com.candy.databasedocuments.entity.DatabaseConfig;
import com.candy.databasedocuments.entity.DcAttr;
import com.candy.databasedocuments.entity.Table;
import com.candy.databasedocuments.service.AbstractDocumentService;
import com.candy.databasedocuments.service.DatabaseService;
import com.candy.databasedocuments.utils.ApplicationContentUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;
import java.util.Optional;

/**
 * @author suYanLong
 * @version 1.0
 * @date 2023/7/5 15:40
 * @Description 入口类
 */
@RestController
public class TestController implements CommandLineRunner {

    static Logger log = LoggerFactory.getLogger(TestController.class);

    @Resource
    DatabaseService databaseService;

    @Resource
    DatabaseConfig databaseConfig;

    @GetMapping("tableToWord")
    public void tableToWord(HttpServletResponse response, HttpServletRequest request) throws Exception {
        //设置生成word 相应头信息
        response.setContentType("application/msword");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("数据库表", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".pdf");
        //获取word  对象
        XWPFDocument document = new XWPFDocument();
        document.write(response.getOutputStream());
    }

    @Override
    public void run(String... args) throws Exception {
        try {
            if (Optional.ofNullable(databaseConfig).map(DatabaseConfig::getDcAttr).map(DcAttr::getLocalGenerated).orElse(false)) {
                log.info("开启本地自动生成文档，参数为：{}", databaseConfig.toString());
                List<Table> tableInfos = databaseService.getTableInfos(databaseConfig);
                AbstractDocumentService abstractDocumentService = (AbstractDocumentService) ApplicationContentUtils.getBean(databaseConfig.getDcAttr().getDocumentType().getDocumentServiceImpl());
                abstractDocumentService.tableToDocument(tableInfos);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
